<template>
  <div class="login-container">
    <div class="login-box">
      <div class="close-btn" @click="$router.push('/')">&times;</div>
      
      <div class="login-tabs">
        <div 
          :class="['tab-item', { active: loginType === 'password' }]"
          @click="loginType = 'password'">
          密码登录
        </div>
        <div 
          :class="['tab-item', { active: loginType === 'sms' }]"
          @click="loginType = 'sms'">
          短信登录
        </div>
      </div>

      <!-- 密码登录表单 -->
      <div v-if="loginType === 'password'" class="login-form">
        <div class="form-item">
          <input 
            type="text" 
            v-model="passwordForm.username" 
            placeholder="请输入用户名">
        </div>
        <div class="form-item">
          <input 
            :type="showPassword ? 'text' : 'password'" 
            v-model="passwordForm.password" 
            placeholder="请输入密码">
          <span 
            class="toggle-password"
            @click="showPassword = !showPassword">
            {{ showPassword ? '👁️' : '👁️‍🗨️' }}
          </span>
        </div>
        <div class="form-options">
          <label class="remember-password">
            <input type="checkbox" v-model="rememberPassword">
            <span>记住密码</span>
          </label>
          <a href="#" class="forget-password">忘记密码？</a>
        </div>
        <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
        <button class="login-btn" @click="handlePasswordLogin" :disabled="isLoading">
          {{ isLoading ? '登录中...' : '登录' }}
        </button>
      </div>

      <!-- 短信登录表单 -->
      <div v-else class="login-form">
        <div class="form-item">
          <input 
            type="text" 
            v-model="smsForm.phone" 
            placeholder="请输入手机号"
            @input="errorMessage = ''">
        </div>
        <div class="form-item verification-code">
          <input 
            type="text" 
            v-model="smsForm.code" 
            placeholder="请输入验证码"
            @input="errorMessage = ''">
          <button 
            class="send-code-btn" 
            :disabled="countdown > 0 || isLoading"
            @click="handleSendCode">
            <span v-if="isLoading">发送中...</span>
            <span v-else>{{ countdown > 0 ? `${countdown}s后重新获取` : '获取验证码' }}</span>
          </button>
        </div>
        <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
        <button class="login-btn" @click="handleSmsLogin" :disabled="isLoading">
          {{ isLoading ? '登录中...' : '登录' }}
        </button>
      </div>

      <div class="login-footer">
        <div class="wechat-login">
          <img src="../assets/wechat-icon.png" alt="微信登录">
          <span>微信登录</span>
        </div>
        <div class="register-link">
          没有账号，<router-link to="/register" class="link">立即注册</router-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: 'http://127.0.0.1:8000',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json'
  },
  withCredentials: true // 允许跨域携带cookie
})

const router = useRouter()
const loginType = ref('password')
const showPassword = ref(false)
const countdown = ref(0)
const rememberPassword = ref(false)
const errorMessage = ref('')
const isLoading = ref(false)
let timer = null

const passwordForm = ref({
  username: '',
  password: ''
})

const smsForm = ref({
  phone: '',
  code: ''
})

// 检查本地存储的登录信息
onMounted(() => {
  // 优先检查 localStorage 中的记住密码信息
  const savedLoginInfo = localStorage.getItem('loginInfo')
  if (savedLoginInfo) {
    const { username, password, remember } = JSON.parse(savedLoginInfo)
    passwordForm.value.username = username
    passwordForm.value.password = password
    rememberPassword.value = remember
  }
})

// 保存登录信息到存储
const saveLoginInfo = (loginData) => {
  if (rememberPassword.value) {
    // 如果勾选了记住密码，使用 localStorage 持久化存储
    localStorage.setItem('token', loginData.token)
    localStorage.setItem('userId', loginData.userId)
    localStorage.setItem('username', loginData.username)
    localStorage.setItem('loginInfo', JSON.stringify({
      username: passwordForm.value.username,
      password: passwordForm.value.password,
      remember: true
    }))
  } else {
    // 如果没有勾选记住密码，使用 sessionStorage 临时存储
    sessionStorage.setItem('token', loginData.token)
    sessionStorage.setItem('userId', loginData.userId)
    sessionStorage.setItem('username', loginData.username)
    // 清除可能存在的本地存储信息
    localStorage.removeItem('loginInfo')
    localStorage.removeItem('token')
    localStorage.removeItem('userId')
    localStorage.removeItem('username')
  }
}

// 密码登录
const handlePasswordLogin = async () => {
  if (!passwordForm.value.username || !passwordForm.value.password) {
    errorMessage.value = '请输入用户名和密码'
    return
  }

  try {
    isLoading.value = true
    errorMessage.value = ''
    
    const response = await api.post('/users/login/', {
      username: passwordForm.value.username,
      password: passwordForm.value.password
    })

    if (response.data.code === 1) {
      // 保存登录信息
      saveLoginInfo(response.data.data)
      // 登录成功，跳转到首页
      router.push('/')
    } else {
      errorMessage.value = response.data.message || '登录失败'
    }
  } catch (error) {
    console.error('登录错误：', error)
    errorMessage.value = error.response?.data?.message || '登录失败，请稍后重试'
  } finally {
    isLoading.value = false
  }
}

// 验证手机号格式
const validatePhone = (phone) => {
  const phoneRegex = /^1\d{10}$/
  return phoneRegex.test(phone)
}

// 发送验证码
const handleSendCode = async () => {
  // 如果正在倒计时，直接返回
  if (countdown.value > 0) return

  // 验证手机号
  if (!smsForm.value.phone) {
    errorMessage.value = '请输入手机号'
    return
  }
  if (!validatePhone(smsForm.value.phone)) {
    errorMessage.value = '请输入正确的手机号'
    return
  }

  try {
    isLoading.value = true
    errorMessage.value = ''
    
    const response = await api.post('/users/sms/code/', {
      mobile: smsForm.value.phone
    })

    if (response.data.code === 1) {
      // 发送成功，开始倒计时
      countdown.value = 60
      timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    } else {
      errorMessage.value = response.data.message
    }
  } catch (error) {
    console.error('发送验证码错误：', error)
    errorMessage.value = error.response?.data?.message || '发送失败，请稍后重试'
  } finally {
    isLoading.value = false
  }
}

// 短信登录
const handleSmsLogin = async () => {
  if (!smsForm.value.phone || !smsForm.value.code) {
    errorMessage.value = '请输入手机号和验证码'
    return
  }

  if (!validatePhone(smsForm.value.phone)) {
    errorMessage.value = '请输入正确的手机号'
    return
  }

  try {
    isLoading.value = true
    errorMessage.value = ''
    
    const response = await api.post('/users/mobile/login/', {
      mobile: smsForm.value.phone,
      code: smsForm.value.code
    })

    if (response.data.code === 1) {
      // 保存登录信息
      saveLoginInfo(response.data.data)
      // 登录成功，跳转到首页
      router.push('/')
    } else {
      errorMessage.value = response.data.message || '登录失败'
    }
  } catch (error) {
    console.error('短信登录错误：', error)
    errorMessage.value = error.response?.data?.message || '登录失败，请稍后重试'
  } finally {
    isLoading.value = false
  }
}

// 组件销毁时清除定时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>

<style scoped>
.login-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-box {
  width: 400px;
  background: white;
  border-radius: 8px;
  padding: 30px;
  position: relative;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.close-btn {
  position: absolute;
  top: 16px;
  right: 16px;
  font-size: 24px;
  color: #999;
  cursor: pointer;
  line-height: 1;
}

.login-tabs {
  display: flex;
  border-bottom: 1px solid #eee;
  margin-bottom: 30px;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 15px 0;
  color: #666;
  cursor: pointer;
  position: relative;
  font-size: 16px;
}

.tab-item.active {
  color: #ff9900;
  font-weight: 500;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  right: 0;
  height: 2px;
  background: #ff9900;
}

.login-form {
  margin-bottom: 30px;
}

.form-item {
  position: relative;
  margin-bottom: 20px;
}

.form-item input {
  width: 100%;
  height: 44px;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 0 15px;
  font-size: 14px;
}

.form-item input:focus {
  border-color: #ff9900;
  outline: none;
}

.toggle-password {
  position: absolute;
  right: 15px;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
  color: #999;
}

.verification-code {
  display: flex;
  gap: 10px;
}

.verification-code input {
  flex: 1;
}

.send-code-btn {
  width: 120px;
  height: 44px;
  border: none;
  background: #ff9900;
  color: white;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.send-code-btn:disabled {
  background: #ffd480;
  cursor: not-allowed;
}

.login-btn {
  width: 100%;
  height: 44px;
  border: none;
  background: #ff9900;
  color: white;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  margin-top: 30px;
}

.login-btn:hover {
  background: #ff8800;
}

.login-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.wechat-login {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
  cursor: pointer;
}

.wechat-login img {
  width: 24px;
  height: 24px;
}

.register-link {
  color: #666;
  font-size: 14px;
}

.link {
  color: #ff9900;
  text-decoration: none;
}

.link:hover {
  text-decoration: underline;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  font-size: 14px;
}

.remember-password {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #666;
  cursor: pointer;
}

.remember-password input[type="checkbox"] {
  width: 16px;
  height: 16px;
  margin: 0;
  cursor: pointer;
  accent-color: #ff9900;
}

.forget-password {
  color: #666;
  text-decoration: none;
}

.forget-password:hover {
  color: #ff9900;
}

.error-message {
  color: #ff4d4f;
  font-size: 14px;
  margin: 8px 0;
  text-align: center;
}

.login-btn:disabled {
  background: #ffd480;
  cursor: not-allowed;
}
</style> 